/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { CoreTask, TaskState, WorkerPoolDelegator } from '@ohos/hvigor';
import { ProjectConfig } from '@ohos/hvigor-arkts-compose';
import path from 'path';

import { OhosLogger } from '../../utils/log/ohos-logger.js';

import { copyByCopyOptions } from './copy-job.js';

/**
 * 用来向线程池提交一个copy的任务 copy什么可以通过参数指定
 */
export class CopyWorker {
  /**
   * 向线程池提交执行copy的任务
   *
   * @param task task
   * @param workerPool 线程池
   * @param logger 日志
   * @param config 编译参数
   * @param callback 编译后的回调函数，其入参是void
   * @param targetWorkers 目标worker
   */
  public static async submitCopyResourcesWork(
    task: CoreTask,
    workerPool: WorkerPoolDelegator,
    logger: OhosLogger,
    config: ProjectConfig,
    callback?: Function,
    targetWorkers?: number[],
  ) {
    logger.debug(`CopyResources startTime: ${process.hrtime.bigint()}`);
    const tcb = workerPool.submit(task, path.resolve(__dirname, 'copy-job.js', 'copyByCopyOptions'), {
      workInput: config,
      callback: callback,
      targetWorkers: targetWorkers,
    });
    if (tcb.getState() === TaskState.REJECT) {
      logger.debug('Worker dispatch failed, running copy resources on main thread.');
      await copyByCopyOptions(config)
        .then(() => {
          callback?.();
        })
        .catch((reason) => {
          throw reason;
        });
      return null;
    }
    return tcb.getId();
  }
}
